package com.example.testrecorder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.Manifest;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testrecorder.domain.Issue;
import com.example.testrecorder.domain.SelectItem;
import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.CallSystemCameraOrAlbum;
import com.example.testrecorder.utils.LogUtil;
import com.example.testrecorder.utils.MyTextWatcher;
import com.example.testrecorder.utils.SelectDialog;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

public class AddRecordActivity extends BaseActivity implements AdapterView.OnItemSelectedListener,View.OnClickListener {
    private Toolbar toolbar;
    private Spinner platformSp,frequencySp,severitySp,solvedSp;
    private ArrayList<String> platformList,frequencyList,severityList,solvedList;
    private String platform="IOS和Android";
    private String frequency="高";
    private String severity="高";
    private String solved="未解决";
    private EditText titleEt,contentEt;
    private LinearLayout pictureLl;
    private ImageView iv;
    private SelectDialog selectDialog;
    private File imgFile;
    private String imgPathStr="";
    private TextView selectTv;
    private View picLine;
    private static final int CHOOSE_FROM_ALBUM=2;
    private static final String TAG = "AddRecordActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_record);
        initView();
    }

    private void initView() {
        picLine=findViewById(R.id.picLine);
        iv=findViewById(R.id.iv);
        selectTv=findViewById(R.id.selectTv);
        pictureLl=findViewById(R.id.pictureLl);
        pictureLl.setOnClickListener(this);
        titleEt=findViewById(R.id.titleEt);
        titleEt.addTextChangedListener(new MyTextWatcher(titleEt,this));
        contentEt=findViewById(R.id.contentEt);
        platformSp=findViewById(R.id.platformSp);
        platformList = new ArrayList<>();
        platformList.add("IOS和Android");
        platformList.add("IOS");
        platformList.add("Android");
        ArrayAdapter<String> platformAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, platformList);
        platformAdapter.setDropDownViewResource(R.layout.issue_field_item);
        platformSp.setAdapter(platformAdapter);
        platformSp.setOnItemSelectedListener(this);
        frequencySp=findViewById(R.id.frequencySp);
        frequencyList = new ArrayList<>();
        frequencyList.add("高");
        frequencyList.add("中");
        frequencyList.add("低");
        ArrayAdapter<String> frequencyAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, frequencyList);
        frequencyAdapter.setDropDownViewResource(R.layout.issue_field_item);
        frequencySp.setAdapter(frequencyAdapter);
        frequencySp.setOnItemSelectedListener(this);
        severitySp=findViewById(R.id.severitySp);
        severityList = new ArrayList<>();
        severityList.add("高");
        severityList.add("中");
        severityList.add("低");
        ArrayAdapter<String> severityAdapter = new ArrayAdapter<>(this, R.layout.issue_field_item, severityList);
        severityAdapter.setDropDownViewResource(R.layout.issue_field_item);
        severitySp.setAdapter(severityAdapter);
        severitySp.setOnItemSelectedListener(this);
        solvedSp=findViewById(R.id.solvedSp);
        solvedList = new ArrayList<>();
        solvedList.add("未解决");
        solvedList.add("已解决");
        solvedList.add("无需解决");
        ArrayAdapter<String> solvedAdapter = new ArrayAdapter<String>(this, R.layout.issue_field_item, solvedList);
        solvedAdapter.setDropDownViewResource(R.layout.issue_field_item);
        solvedSp.setAdapter(solvedAdapter);
        solvedSp.setOnItemSelectedListener(this);
        toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        LogUtil.logD(TAG,"父布局的id："+parent.getId());
        switch (parent.getId()){
            case R.id.platformSp:
                platform = platformList.get(position);
                break;
            case R.id.frequencySp:
                frequency=frequencyList.get(position);
                break;
            case R.id.severitySp:
                severity=severityList.get(position);
                break;
            case R.id.solvedSp:
                solved=solvedList.get(position);
                break;
            default:
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.save:
                Issue issue=new Issue(MyApplication.currUser.getId(),titleEt.getText().toString(),
                        contentEt.getText().toString(),new Date(),new Date(),solved,severity,imgPathStr,frequency,platform);
                boolean save = issue.save();
                if(save){
                    Toast.makeText(AddRecordActivity.this,"保存成功！",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(AddRecordActivity.this,MainActivity.class));
                }else {
                    Toast.makeText(AddRecordActivity.this,"保存失败！",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id==R.id.pictureLl){
            ArrayList<SelectItem> list=new ArrayList<>();
            list.add(new SelectItem(R.drawable.icons8_google_images_96px,"拍照"));
            list.add(new SelectItem(R.drawable.icons8_picture_96px,"从相册中选择"));
            selectDialog=new SelectDialog(AddRecordActivity.this, list, new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(selectDialog!=null){
                        selectDialog.dismiss();
                    }
                    if(position==0){
                        if(Build.VERSION.SDK_INT>=23){//6.0以上版本，加入动态权限申请
                            int i1 = ContextCompat.checkSelfPermission(AddRecordActivity.this, Manifest.permission.CAMERA);
                            int i2 = ContextCompat.checkSelfPermission(AddRecordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);//写权限包括了读权限
                            if(i1!= PackageManager.PERMISSION_GRANTED||i2!=PackageManager.PERMISSION_GRANTED){//没有授予相机权限或读写权限
                                //请求读写权限、相机权限
                                ActivityCompat.requestPermissions(AddRecordActivity.this,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                            }else{//授予了相机权限或读写权限
                                bootCamera();
                            }
                        }else {//6.0以下版本，直接打开相机
                            bootCamera();
                        }
                    }else if(position==1){
                        //如果未授予读写SD卡的权限
                        if(ContextCompat.checkSelfPermission(AddRecordActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions(AddRecordActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},CHOOSE_FROM_ALBUM);
                        }else {//授予了读写SD卡的权限
                            openAlbum();//打开相册
                        }
                    }

                }
            });
        }
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_FROM_ALBUM); // 打开相册
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==1){
            if(grantResults.length==2&&grantResults[0]==PackageManager.PERMISSION_GRANTED&&grantResults[1]==PackageManager.PERMISSION_GRANTED){//如果用户确认授予读写权限、相机权限
                bootCamera();
            }
        }else if(requestCode==CHOOSE_FROM_ALBUM){
            if(grantResults.length==1&&grantResults[0]==PackageManager.PERMISSION_GRANTED){//如果用户授予了读写SD卡的权限
                openAlbum();
            }else {
                Toast.makeText(AddRecordActivity.this,"您尚未授予读写SD卡的权限，无法打开相册！",Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 打开相机
     */
    private void bootCamera(){
        imgFile = CallSystemCameraOrAlbum.OpenCamera(AddRecordActivity.this);//调用工具类来拍照
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CallSystemCameraOrAlbum.CAMERA_REQUEST_CODE){
            if(imgFile.exists()){
                selectTv.setText(imgFile.getAbsolutePath());//将照片的存储路径显示到界面上
                imgPathStr=imgFile.getAbsolutePath();//给照片的路径变量赋值，以便将该路径保存到SQLite数据库
                LogUtil.logD(TAG,"图片的路径是："+imgFile.getAbsolutePath());
                Bitmap bitmapFromPath = BitmapUtil.getBitmapFromPath(imgPathStr);
                iv.setImageBitmap(bitmapFromPath);
                iv.setVisibility(View.VISIBLE);
                picLine.setVisibility(View.VISIBLE);
            }else{
                Toast.makeText(AddRecordActivity.this,"您尚未完成拍照。",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode==CHOOSE_FROM_ALBUM){
            if(resultCode==RESULT_OK){
                if(Build.VERSION.SDK_INT>=19){
                    handleImageOnKitKat(data);// 4.4 及以上系统使用这个方法处理图片
                }else {
                    handleImageBeforeKitKat(data);// 4.4 以下系统使用这个方法处理图片
                }
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是 document 类型的 Uri ，则通过 document id 处理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1]; // 解析出数字格式的 id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.
                    getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                        imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri ，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 file 类型的 Uri ，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath); // 根据图片路径显示图片
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过 Uri 和 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.
                        Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            selectTv.setText(imagePath);
            imgPathStr=imagePath;
            iv.setImageBitmap(bitmap);
            iv.setVisibility(View.VISIBLE);
            picLine.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show();
        }
    }
}